import WsBaseClass from './wsBase.js';


// 需求是，用户userid更换，历史记录清零 
// web端，随机生成userid

class ChatWsClass extends WsBaseClass {
  constructor(url,characterId,content,userId = null) 
  {
    super(url);
    this.characterId = characterId;
    this.content = content;
    this.userId = userId;
    this.contents = [];
    this.temp_str = "";
    this.splitSymbol = ["?","。","！"];
    this.maxSplitNum = 4;
  }
  onOpen(event){
    // 发送验证信息，组装本次沟通的内容
    let data = {
      "characterId" : this.characterId,
      "userId" : this.userId,
      "content" : this.content
    };
    this.send(data);
  }
  onMessage(event)
  {
    let _self = this;
    let data =  JSON.parse(event.data);
    if(data.status)
    {
      if(data.status == 200)
      {
        let content = data.content;
        if(content)
        {
          this.contents.push(content);
          this.temp_str += content;
          this.checkText();
        }
      }else if(data.status == 300)
      {
        // 本次事件流结束
        _self.createAudio(this.temp_str);
        this.ws.close();
      }else{
        console.log(data.message)
      }
    }
  }
  send(data)
  {
    this.ws.send(JSON.stringify(data));
  }

  // 检查是否需要分割进行语音合成
  checkText()
  {
    let _self = this;
    let maxLimit = 0;

    this.splitSymbol.forEach((item)=>{
      let num = _self.temp_str.indexOf(item)
      if(num > maxLimit) maxLimit = num;
    })
   
    if (maxLimit > 0 && _self.temp_str.length > this.maxSplitNum)
    {
      let msg = _self.temp_str.slice(0,maxLimit+1);
      _self.temp_str = _self.temp_str.slice(maxLimit+1,_self.temp_str.length);
      // console.log(maxLimit)
      // console.log(msg)
      // console.log(_self.temp_str)
      _self.createAudio(msg);
    }
  }


  createAudio(msg){}



}



export default ChatWsClass;